// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import { GameBalance } from "../data/GameBalance";
import AudioManager from "../manager/audio_manager";
import JsonManager from "../manager/json_manager";
import PoolManager from "../manager/pool_manager";
import StorageManager from "../manager/storage_manager";
import { Utils } from "../utils/utils";
import Enemy from "./Enemy";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Ball extends cc.Component {


    direction;
    timer: number = 0;
    baseSpeed = 600;
    speed: number = 800
    angleOffsetRange;
    atk: number = 6
    baseAtk: number = 6
    id: number = 11
    baseScale = 0.2
    onLoad() {
        this.direction = cc.v2(1, 0); // 初始方向向右
    }



    init() {
        // 从玩家前方随机角度发射
        const randomAngle = cc.misc.degreesToRadians(Utils.getRandomNumInRange(-30, 30)); // 随机角度 -30 到 30
        const initialDirection = cc.v2(1, 1).rotate(randomAngle);
        let skillExtra = JsonManager.instance.getDataByName('skill_extra')
        let skillExtraInfo = skillExtra[this.id]
        let skillLevel = StorageManager.instance.skillLevel[this.id]
        this.timer = StorageManager.instance.ballExistTime;

        this.node.scale = this.baseScale + this.baseScale * (1 + StorageManager.instance.ballStrenth + skillExtraInfo.range * skillLevel)
        this.node.scale = this.baseScale
        this.direction = initialDirection.normalize(); // 设置弹球方向
        // this.atk = Math.ceil(this.baseAtk * (1 + StorageManager.instance.ballStrenth))
        this.speed = this.baseSpeed * (1 + StorageManager.instance.ballSpeed)


        // cc.log("等级atk" + skillExtraInfo.atk * StorageManager.instance.skillLevel[this.id])
        this.atk += GameBalance.calculateSkillAtk(this.id.toString())

    }

    update(dt) {
        // 移动弹球
        const displacement = this.direction.mul(this.speed * dt); // 位移 = 方向向量 * 速度 * 时间
        let timeScal = cc.director.getScheduler().getTimeScale()
        this.node.position = this.node.position.add(displacement);

        // 检测边缘反弹
        this.checkBounds();
        this.timer -= dt * timeScal
        // 检查是否超过 10 秒，销毁弹球
        if (this.timer <= 0) {
            // this.timer=StorageManager.instance.ballCd;
            PoolManager.instance.removeObject(this.node)

        }
    }

    onCollisionEnter(other, self) {
        // cc.log('bullet 打击Enter');
        if (other.node.group === 'Enemy') {
            let enemyScript = other.getComponent(Enemy)
            // this.attackTarget(other.getComponent(Enemy));

            if (enemyScript) {

                enemyScript.takeDamage(this.atk); // 对敌人造成伤害

                // AudioManager.instance.playAudio('ball')
                // cc.log("扩散次数:" + this.spreadCount)
                // if (this.spreadCount > 0) {
                //     // 使用示例：假设原节点是 this.node
                //     this.createCopies(this.node, StorageManager.instance.spreadCount, 10);  // 6 个复制体，均匀分布在半径为 100 的圆形上
                //     // let newtarget = this.setNewTarget();

                //     // if (newtarget != null) {
                //     //     this.target = newtarget;
                //     //     this.isSpreading = true;
                //     //     const targetPosition = this.target.node.position;

                //     //     const directionToTarget = cc.v2(targetPosition.x - this.node.position.x, targetPosition.y - this.node.position.y).normalize();

                //     //     if (this.rb2d) {
                //     //         this.rb2d.linearVelocity = cc.v2(0, 0);
                //     //         const force = directionToTarget.mul(this.bulletSpeed); // 根据方向和力大小计算力向量
                //     //         this.rb2d.applyForce(force, this.rb2d.getWorldCenter(), true); // 施加力
                //     //     }
                //     // }
                // }

            }

        }
    }

    checkBounds() {
        const screenBounds = cc.view.getVisibleSize();
        const halfWidth = screenBounds.width / 2;
        const halfHeight = screenBounds.height / 2;

        let hasBounced = false;

        // 判断是否超出屏幕边界并反弹
        if (this.node.x > halfWidth || this.node.x < -halfWidth) {
            this.direction.x *= -1; // X 方向反转
            hasBounced = true;
        }
        if (this.node.y > halfHeight || this.node.y < -halfHeight) {
            this.direction.y *= -1; // Y 方向反转
            hasBounced = true;
        }


    }
}
